﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TS2015.Models;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Text;
using System.Data.OleDb;
using System.Data;

namespace TS2015.Areas.Admin.Controllers
{
    public class CandidateManagementController : Controller
    {
        TS2015Context db = new TS2015Context();
        // GET: Admin/CandidateManagement
        bool CheckHighSchool, CheckProvince, CheckCandidate, CheckCommune;
        string Province;
        int idtruong;
        List<string> error = new List<string>();
        string count;
        public JsonResult GetMajorByPhylum(int manganh)
        {
            var major = from c in db.TbChuyenNganhs
                        where c.IDNganh == manganh
                        select c;
            return Json(new SelectList(major.ToList(), "MaChuyenNganh", "TenChuyenNganh"), JsonRequestBehavior.AllowGet);
        }
        public ActionResult CandidateList()
        {

            Database.SetInitializer<TS2015Context>(null);

            //ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
            ViewBag.ChuyenNganh = db.TbChuyenNganhs.ToList();
            ViewBag.Truong = db.TbTruongTHPTs.ToList();
            ViewBag.Nganh = db.TbNganhs.ToList();
            //ViewBag.Truong = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
            ViewBag.KhuVuc = db.TbKhuVucs.ToList();
            ViewBag.XepLoaiHS = db.TbXepLoaiHS.ToList();
            ViewBag.DanToc = db.TbDanTocs.ToList();
            ViewBag.DoiTuongUuTien = db.TbDoiTuongUuTiens.ToList();
            ViewBag.KhoiThi = db.TbKhoiThis.ToList();
            ViewBag.HeDaoTao = db.TbHeDaoTaos.ToList();
            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }
        public ActionResult GetCandidate()
        {
            var CandidateList = from a in db.TbThiSinhs
                                join b in db.TbDanTocs on a.MaDanToc equals b.MaDanToc
                                join c in db.TbTruongTHPTs on a.IDTruong equals c.IDTruong
                                join d in db.TbTinhs on c.MaTinh equals d.MaTinh
                                join e in db.TbKhuVucs on c.MaKhuVuc equals e.MaKhuVuc
                                join f in db.TbHuyens on a.MaHuyen equals f.MaHuyen
                                join o in db.TbTinhs on f.MaTinh equals o.MaTinh
                                join g in db.TbDoiTuongUuTiens on a.MaDoiTuong equals g.MaDoiTuong
                                join h in db.TbTruongDHs on a.MaTruongDH equals h.MaTruongDH
                                join i in db.TbChuyenNganhs on a.MaChuyenNganh equals i.MaChuyenNganh
                                join k in db.TbNganhs on i.IDNganh equals k.IDNganh
                                join l in db.TbKhoiThis on k.MaKhoiThi equals l.MaKhoiThi
                                join m in db.TbHeDaoTaos on a.MaHeDaoTao equals m.MaHeDaoTao
                                select new ResultTK
                                {
                                    MaTS = a.MaTS,
                                    HoDem = a.HoDem,
                                    Ten = a.Ten,
                                    FullName = a.HoDem + a.Ten,
                                    SBD = a.SBD,
                                    MaDanToc = a.MaDanToc,
                                    TenDanToc = b.TenDanToc,
                                    GioiTinh = a.GioiTinh,
                                    SoDienThoai = a.SoDienThoai,
                                    Email = a.Email,
                                    NgaySinh = a.NgaySinh,
                                    IDTruong = a.IDTruong,
                                    MaTruong = c.MaTruong,
                                    TenTruong = c.TenTruong,
                                    MaHuyen = a.MaHuyen,
                                    TenHuyen = f.TenHuyen,
                                    DiaChi = a.DiaChi,
                                    DiemLop10 = a.DiemLop10,
                                    DiemLop11 = a.DiemLop11,
                                    DiemLop12 = a.DiemLop12,
                                    DiemTBTHPT = a.DiemTBTHPT,
                                    DiemTBTN = a.DiemTBTN,
                                    MaDoiTuong = a.MaDoiTuong,
                                    TenDoiTuong = g.TenDoiTuong,
                                    MaTinhTruong = c.MaTinh,
                                    TenTinhTruong = d.TenTinh,
                                    MaTinh = f.MaTinh,
                                    TenTinh = o.TenTinh,
                                    MaChuyenNganh = a.MaChuyenNganh,
                                    MaHeDaoTao = a.MaHeDaoTao,
                                    MaKhoiThi = l.MaKhoiThi,
                                    TenKhoiThi = l.TenKhoiThi,
                                    MaNganh = k.MaNganh,
                                    TenChuyenNganh = i.TenChuyenNganh,
                                    TenNganh = k.TenNganh,
                                    TenHeDaoTao = m.TenHeDaoTao,
                                    NgayDangKy = a.NgayDangKi,
                                    NgayDongTien = a.NgayDongTien,
                                    NgayHoanThanhDK = a.NgayHoanThanhDK,
                                    NamTotNghiep = a.NamTotNghiep
                                };
            return Json(CandidateList.ToList(),JsonRequestBehavior.AllowGet);
        }
        public ActionResult EditingPopup_ReadCandidateList([DataSourceRequest] DataSourceRequest request)
        {
            var CandidateList = from a in db.TbThiSinhs
                                join b in db.TbDanTocs on a.MaDanToc equals b.MaDanToc
                                join c in db.TbTruongTHPTs on a.IDTruong equals c.IDTruong
                                join d in db.TbTinhs on c.MaTinh equals d.MaTinh
                                join e in db.TbKhuVucs on c.MaKhuVuc equals e.MaKhuVuc
                                join f in db.TbHuyens on a.MaHuyen equals f.MaHuyen
                                join o in db.TbTinhs on f.MaTinh equals o.MaTinh
                                join g in db.TbDoiTuongUuTiens on a.MaDoiTuong equals g.MaDoiTuong
                                join h in db.TbTruongDHs on a.MaTruongDH equals h.MaTruongDH
                                join i in db.TbChuyenNganhs on a.MaChuyenNganh equals i.MaChuyenNganh
                                join k in db.TbNganhs on i.IDNganh equals k.IDNganh
                                join l in db.TbKhoiThis on k.MaKhoiThi equals l.MaKhoiThi
                                join m in db.TbHeDaoTaos on a.MaHeDaoTao equals m.MaHeDaoTao
                                select new ResultTK
                                {
                                    MaTS = a.MaTS,
                                    HoDem = a.HoDem,
                                    Ten = a.Ten,
                                    FullName = a.HoDem + a.Ten,
                                    SBD = a.SBD,
                                    MaDanToc = a.MaDanToc,
                                    TenDanToc = b.TenDanToc,
                                    GioiTinh = a.GioiTinh,
                                    SoDienThoai = a.SoDienThoai,
                                    Email = a.Email,
                                    NgaySinh = a.NgaySinh,
                                    IDTruong = a.IDTruong,
                                    MaTruong = c.MaTruong,
                                    TenTruong = c.TenTruong,
                                    MaHuyen = a.MaHuyen,
                                    TenHuyen = f.TenHuyen,
                                    DiaChi = a.DiaChi,
                                    DiemLop10 = a.DiemLop10,
                                    DiemLop11 = a.DiemLop11,
                                    DiemLop12 = a.DiemLop12,
                                    DiemTBTHPT = a.DiemTBTHPT,
                                    DiemTBTN = a.DiemTBTN,
                                    MaDoiTuong = a.MaDoiTuong,
                                    TenDoiTuong = g.TenDoiTuong,
                                    MaTinhTruong = c.MaTinh,
                                    TenTinhTruong = d.TenTinh,
                                    MaTinh = f.MaTinh,
                                    TenTinh = o.TenTinh,
                                    MaChuyenNganh = a.MaChuyenNganh,
                                    MaHeDaoTao = a.MaHeDaoTao,
                                    MaKhoiThi = l.MaKhoiThi,
                                    TenKhoiThi = l.TenKhoiThi,
                                    MaNganh = k.MaNganh,
                                    TenChuyenNganh = i.TenChuyenNganh,
                                    TenNganh = k.TenNganh,
                                    TenHeDaoTao = m.TenHeDaoTao,
                                    NgayDangKy = a.NgayDangKi,
                                    NgayDongTien = a.NgayDongTien,
                                    NgayHoanThanhDK = a.NgayHoanThanhDK
                                };
            return Json(CandidateList.ToDataSourceResult(request));
        }
        public ActionResult EditingPopup_CreateCandidateList([DataSourceRequest] DataSourceRequest request, TbThiSinh data)
        {
            if (data != null && ModelState.IsValid)
            {
                db.TbThiSinhs.Add(data);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult EditingPopup_UpdateCandidateList([DataSourceRequest] DataSourceRequest request, TbThiSinh data)
        {
            if (data != null && ModelState.IsValid)
            {
                db.Entry(data).State = EntityState.Modified;
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }

        public ActionResult EditingPopup_DestroyCandidateList([DataSourceRequest] DataSourceRequest request, TbThiSinh data)
        {
            if (data != null)
            {
                TbNguoiDung itemuser = db.TbNguoiDungs.FirstOrDefault(item => item.TenDangNhap == data.MaTS);
                if (itemuser != null)
                {
                    db.TbNguoiDungs.Remove(itemuser);
                }
                var itemtraining = db.TbThiSinh_HeDaoTaos.Where(item => item.MaTS == data.MaTS);
                if (itemtraining != null)
                {
                    foreach (var a in itemtraining)
                    {
                        db.TbThiSinh_HeDaoTaos.Remove(a);
                    }
                }
                var itemmark = db.TbDiemTotNghieps.Where(item => item.MaTS == data.MaTS);
                if (itemmark != null)
                {
                    foreach (var a in itemmark)
                    {
                        db.TbDiemTotNghieps.Remove(a);
                    }
                }
                TbThiSinh itemdata = db.TbThiSinhs.FirstOrDefault(item => item.MaTS == data.MaTS);
                db.TbThiSinhs.Remove(itemdata);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }

        private void SaveChanges(DbContext context)
        {
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                StringBuilder sb = new StringBuilder();

                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                        sb.AppendLine();
                    }
                }

                throw new DbEntityValidationException(
                    "Entity Validation Failed - errors follow:\n" +
                    sb.ToString(), ex
                ); // Add the original exception as the innerException
            }
        }
        public ActionResult Excel_Export_Save(string contentType, string base64, string fileName)
        {
            var fileContents = Convert.FromBase64String(base64);

            return File(fileContents, contentType, fileName);
        }
        public ActionResult ImportCandidate(HttpPostedFileBase FileImport)
        {

            bool state = false;
            string mess = "";
            if (FileImport != null)
            {
                // thuc hien thao tac tai day
                if (FileImport.ContentLength > 0)
                {
                    string Extension = System.IO.Path.GetExtension(FileImport.FileName);
                    if (Extension == ".xls" || Extension == ".xlsx")
                    {
                        string path = string.Concat(Server.MapPath("~/Uploads/File/" + DateTime.Now.ToString("MMddyyyyHHmmssfff") + FileImport.FileName));
                        //if (System.IO.File.Exists(path))
                        //{

                        //    System.IO.File.Delete(path);
                        //}
                        FileImport.SaveAs(path);
                        OleDbConnection oledbcon = new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=" + path + ";extended properties=excel 12.0;");
                        oledbcon.Open();
                        DataTable ExcelSheets = oledbcon.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                        string SpreadSheetName = ExcelSheets.Rows[0]["TABLE_NAME"].ToString();
                        OleDbCommand oledbcmd = new OleDbCommand("Select * from [" + SpreadSheetName + "]", oledbcon);
                        OleDbDataAdapter oledbda = new OleDbDataAdapter(oledbcmd);
                        DataTable dt = new DataTable();
                        TbThiSinh item;
                        TbNguoiDung nguoidung;
                        oledbda.Fill(dt);
                        var ListHighSchool = (from c in db.TbTruongTHPTs select c).ToList();
                        var ListProvince = (from c in db.TbTinhs select c).ToList();
                        var ListCandidate = (from c in db.TbThiSinhs select c).ToList();
                        var ListCommune = (from c in db.TbHuyens select c).ToList();
                        //System.IO.File.Delete(path);
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count - 1; i++)
                            {
                                string Truong = dt.Rows[i]["lop12"].ToString().Trim().Substring(2, dt.Rows[i]["lop12"].ToString().Length - 2);
                                string Ngay = dt.Rows[i]["ngaysinh"].ToString().Trim().Substring(0, 2);
                                string Thang = dt.Rows[i]["ngaysinh"].ToString().Trim().Substring(2, 2);
                                string Nam = dt.Rows[i]["ngaysinh"].ToString().Trim().Substring(4, 2);
                                string NgaySinh = (Thang + "/" + Ngay + "/19" + Nam);

                                foreach (var a in ListHighSchool)
                                {
                                    CheckHighSchool = false;
                                    if (a.MaTruong.ToLower().Trim() == Truong)
                                    {
                                        CheckHighSchool = true;
                                        idtruong = a.IDTruong;
                                        break;
                                    }
                                }

                                foreach (var a in ListProvince)
                                {
                                    CheckProvince = false;
                                    if (a.MaTinh.ToLower().Trim() == dt.Rows[i]["tinh"].ToString().ToLower().Trim())
                                    {
                                        CheckProvince = true;
                                        Province = a.TenTinh.Trim();
                                        break;
                                    }
                                }
                                // Chưa có dữ liệu chuẩn về tỉnh huyện để test
                                foreach (var a in ListCommune)
                                {
                                    CheckCommune = false;
                                    if (a.MaHuyen.ToLower().Trim() == dt.Rows[i]["huyen"].ToString().ToLower().Trim())
                                    {

                                        CheckCommune = true;
                                        //Province = a.TenTinh.Trim();
                                        break;
                                    }
                                }
                                foreach (var a in ListCandidate)
                                {
                                    CheckCandidate = false;
                                    if (a.CMND.ToLower().Trim() == dt.Rows[i]["sobaodanh"].ToString().ToLower().Trim())
                                    {
                                        CheckCandidate = true;
                                        break;
                                    }
                                }

                                //try
                                //{
                                if (CheckProvince && CheckHighSchool && CheckCommune && !CheckCandidate)
                                {
                                    item = new TbThiSinh();
                                    item.MaTS = GetID();
                                    item.IDTruong = idtruong;
                                    item.HoDem = dt.Rows[i]["ho"].ToString().Trim();
                                    item.Ten = dt.Rows[i]["ten"].ToString().Trim();
                                    if (dt.Rows[i]["phai"].ToString().Trim() == "0")
                                    {
                                        item.GioiTinh = GioiTinh.Nam;
                                    }
                                    else
                                    {
                                        item.GioiTinh = GioiTinh.Nữ;
                                    }
                                    //item.NgaySinh = DateTime.Parse(dt.Rows[i]["ngaysinh"].ToString().Trim());
                                    item.NgaySinh = DateTime.Parse(NgaySinh);
                                    item.MaDanToc = 1;
                                    item.DiaChi = Province;
                                    item.CMND = dt.Rows[i]["sobaodanh"].ToString().Trim();
                                    item.SBD = dt.Rows[i]["sobaodanh"].ToString().Trim();
                                    item.MaDoiTuong = Int32.Parse(dt.Rows[i]["nhomut"].ToString().Trim());
                                    //item.MaKhoiThi = dt.Rows[i]["khoi"].ToString().Trim();
                                    item.MaHeDaoTao = 1;
                                    item.MaChuyenNganh = "1";
                                    item.TrangThaiDongTien = true;
                                    item.NgayDangKi = DateTime.Now;
                                    item.LanSuaCuoi = DateTime.Now;
                                    item.MaTruongDH = "1";
                                    //item.TbTruongTHPT
                                    db.TbThiSinhs.Add(item);
                                    item.Email = "nhatduocbitien@gmail.com";
                                    item.SoDienThoai = "0978654123";
                                    item.MaHuyen = dt.Rows[i]["huyen"].ToString().Trim();
                                    //insert Tài khoản
                                    nguoidung = new TbNguoiDung { TenDangNhap = item.MaTS, MaQuyen = 3, MatKhau = DuLieuChung.MaHoaMD5("123456"), RandomPass = "1234zxcv", KhoaTaiKhoan = 0 };
                                    db.TbNguoiDungs.Add(nguoidung);
                                    SaveChanges(db);
                                }
                                else
                                {
                                    error.Add("Lỗi");
                                }

                                //}
                                //catch
                                //{
                                //    continue;
                                //}
                            }
                            for (int k = 0; k < error.Count; k++)
                            {
                                count += " + " + error[k].ToString() + "<br/>";
                            }
                            state = true;
                            mess = "Thực hiện chèn thành công " + (dt.Rows.Count - error.Count - 1) + " bản ghi!";
                            //empData["Message"] = "Lưu thành công!";
                        }
                        else
                        {
                            Response.Write("Không có dữ liệu!");
                        }
                        oledbcon.Close();
                    }
                    else
                    {
                        Response.Write("Bạn phải nhập file định dạng excel!");
                    }
                }
            }
            else
                mess = "Có lỗi.";

            return Json(new { State = state, Message = mess });
        }
        public string GetID()
        {
            string ID = "";
            var MaTS = (from p in db.TbThiSinhs orderby (p.MaTS) descending select p).Take(1).FirstOrDefault();
            int Cuoi;
            string LastID;
            int NextID;

            if (MaTS == null)
            {
                NextID = 1;
            }
            else
            {
                Cuoi = Convert.ToInt32(MaTS.MaTS.ToString().Substring(4)) + 1;
                LastID = Cuoi.ToString();
                if (LastID == null)
                {
                    LastID = DateTime.Now.ToString("yyyy") + "00001";
                }
                NextID = Cuoi;
            }
            ID = DateTime.Now.ToString("yyyy") + NextID.ToString("00000");
            return ID;
        }

        #region Registration

        #region Select Training System
        [HttpGet]
        public ActionResult SelectTrainingSystem()
        {
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");

            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SelectTrainingSystem(string id)
        {
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
            if (ModelState.IsValid)
            {
                int HDT = Int32.Parse(Request.Form["HeDaoTao"]);
                var hedt = db.TbHeDaoTaos.Where(m => m.MaHeDaoTao == HDT).FirstOrDefault().TenHeDaoTao;
                if (hedt.ToLower().Trim() == "Đại học chính quy".ToLower() || hedt.ToLower().Trim() == "Cao đẳng chính quy".ToLower())
                {
                    return RedirectToAction("RegistrationForm", "CandidateManagement", new { TrainingSystem = HDT });
                }
                return RedirectToAction("RegistrationFormVocation", "CandidateManagement", new { TrainingSystem = HDT });
            }

            return PartialView();
        }
        #endregion

        public JsonResult GetPhylumByGroup(int HDT, string makhoithi)
        {

            //int Te = Int32.Parse(Request.Form["lbTrainingSystem"]);
            var LoadTrainingSystem = db.TbHeDaoTaos.Where(m => m.MaHeDaoTao == HDT).FirstOrDefault().TenHeDaoTao;
            var phylumD = db.TbNganhs.Where(m => m.MaNganh.ToString().Contains("D") && m.MaKhoiThi == makhoithi);
            var phylumC = db.TbNganhs.Where(m => m.MaNganh.ToString().Contains("C") && m.MaKhoiThi == makhoithi);
            if (LoadTrainingSystem.ToLower() == "Đại học chính quy".ToLower())
            {
                return Json(new SelectList(phylumD.ToList(), "IDNganh", "TenNganh"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new SelectList(phylumC.ToList(), "IDNganh", "TenNganh"), JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult GetProvinceByCommune(string matinh)
        {
            var commune = from c in db.TbHuyens
                          where c.MaTinh == matinh
                          select c;
            return Json(new SelectList(commune.ToList(), "MaHuyen", "TenHuyen"), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetHighSchoolByProvince(string matinh)
        {
            var highschool = from c in db.TbTruongTHPTs
                             where c.MaTinh == matinh
                             select c;
            return Json(new SelectList(highschool.ToList(), "IDTruong", "TenTruong"), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetGraduateSubjectBySubjectCustom(int mamon)
        {
            var monthi = from c in db.TbMonTotNghieps
                         where c.MaMon != mamon && c.TenMon != "Toán" && c.TenMon != "Tiếng anh" && c.TenMon != "Ngữ Văn"
                         select c;
            return Json(new SelectList(monthi.ToList(), "MaMon", "TenMon"), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetGraduateSubjectByGroup(int mamontuychon, string makhoithi)
        {
            var monthi = from c in db.TbKhoiThi_MonTotNghieps
                         where c.TbMonTotNghiep.TenMon != "Toán" && c.TbMonTotNghiep.TenMon != "Tiếng anh" && c.TbMonTotNghiep.TenMon != "Ngữ Văn"
                               && c.TbMonTotNghiep.MaMon != mamontuychon && c.MaKhoiThi == makhoithi
                         select new
                         {
                             MaMon = c.MaMon,
                             TenMon = c.TbMonTotNghiep.TenMon
                         };

            return Json(monthi, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetGraduateSubjectByGroup2(string MaTS, string makhoithi)
        {
            var monthi = from c in db.TbKhoiThi_MonTotNghieps
                         where c.TbMonTotNghiep.TenMon != "Toán" && c.TbMonTotNghiep.TenMon != "Tiếng anh" && c.TbMonTotNghiep.TenMon != "Ngữ Văn"
                               && c.MaKhoiThi == makhoithi
                         select new
                         {
                             MaMon = c.MaMon,
                             TenMon = c.TbMonTotNghiep.TenMon
                         };
            var ListSubject = from a in db.TbThiSinhs
                              join b in db.TbDiemTotNghieps on a.MaTS equals b.MaTS
                              join c in db.TbMonTotNghieps on b.MaMon equals c.MaMon
                              where a.MaTS == MaTS
                              select b;


            return Json(monthi, JsonRequestBehavior.AllowGet);
        }
        #region Registration Form
        public ActionResult RegistrationForm(string MaTS)
        {
            //ViewBag.HeDaoTaoKhac = Enum.GetValues(typeof(HeDaoTaoKhac));
            ViewBag.HeTrungCap = false;
            ViewBag.HeCaoDang = false;


            TbThiSinh ThiSinh = new TbThiSinh();
            if (ModelState.IsValid)
            {
                if (Session["TenDangNhap"] != null)
                    MaTS = MaTS ?? Session["TenDangNhap"].ToString();

                if (ThiSinh.MaTS == null)
                {
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                    ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                    ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
                    ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                    ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
                    ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
                    ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
                    ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
                    ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
                    //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
                    ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
                    ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
                    ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
                    ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                }
                else
                {
                    ThiSinh = db.TbThiSinhs.First(e => e.MaTS == MaTS);
                    var mamon = db.TbDiemTotNghieps.Include(m => m.MaTS).Where(m => m.MaTS == ThiSinh.MaTS).FirstOrDefault().MaMon;
                    ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.ToList(), "MaMon", "TenMon", mamon);
                    var matinh = db.TbThiSinhs.Include(m => m.MaHuyen).Where(m => m.MaTS == ThiSinh.MaTS).FirstOrDefault().TbHuyen.MaTinh;
                    ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh", matinh);
                    ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen", ThiSinh.MaHuyen);
                    var manganh = (from m in db.TbChuyenNganhs where (m.MaChuyenNganh == ThiSinh.MaChuyenNganh) select m).First().IDNganh;
                    ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh", manganh);
                    ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh", ThiSinh.MaChuyenNganh);
                    var matinh2 = db.TbThiSinhs.Include(m => m.IDTruong).Where(m => m.MaTS == ThiSinh.MaTS).FirstOrDefault().TbHuyen.MaTinh;
                    ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong", ThiSinh.IDTruong);
                    ViewBag.TruongHD = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH", ThiSinh.MaTruongDH);
                    ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh", matinh2);
                    //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc", ThiSinh.MaKhuVuc);
                    ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS", ThiSinh.MaXepLoaiHS);
                    ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc", ThiSinh.MaDanToc);
                    ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong", ThiSinh.MaDoiTuong);
                    var IDNganh = db.TbThiSinhs.Include(m => m.TbChuyenNganh).Where(m => m.MaTS == ThiSinh.MaTS).FirstOrDefault().TbChuyenNganh.IDNganh;
                    var makhoithi = db.TbChuyenNganhs.Include(m => m.TbNganh).Where(m => m.IDNganh == IDNganh).FirstOrDefault().TbNganh.MaKhoiThi;
                    ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi", makhoithi);
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao", ThiSinh.MaHeDaoTao);
                }
            }


            if (Request.IsAjaxRequest() || MaTS != null)
                return PartialView(ThiSinh);

            return View(ThiSinh);
        }

        [HttpPost]
        public ActionResult RegistrationForm(TbThiSinh item, bool HeTrungCap = false, bool HeCaoDang = false)
        {
            if (item != null)
            {
                TbNguoiDung nguoidung;
                TbDiemTotNghiep diem;
                item.NgayDangKi = DateTime.Now;
                item.LanSuaCuoi = DateTime.Now;
                //item.NgaySinh = DateTime.Now;
                if (item.MaTS != null)
                {
                    db.Entry(item).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else
                {
                    //if (ModelState.IsValid)
                    //{
                    item.MaTS = GetID();
                    item.NgayDongTien = DateTime.Now;
                    item.NgayHoanThanhDK = DateTime.Now;

                    if (Request.Form["TrangThaiDangKi"] == "0")
                    {

                    }
                    else if (Request.Form["TrangThaiDangKi"] == "1")
                    {
                        item.MaTruongDH = db.TbTruongDHs.Where(m => m.TenTruongDH.ToLower() == "đại học điện lực").FirstOrDefault().MaTruongDH;
                        // Điểm 3 môn Toán, Văn, Anh
                        string[] MangMaMon1 = Request.Form["SubjectRecruitmentBasic"].Split(',');
                        string[] MangDiemMon1 = Request.Form["MarkRecruitmentBasic"].Split(',');
                        string ten = "";
                        for (int i = 0; i < MangMaMon1.Length; i++)
                        {
                            if (MangDiemMon1[i].Trim() != "")
                            {
                                ten = MangMaMon1[i];
                                var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon, Diem = double.Parse(MangDiemMon1[i].Trim()) };
                                db.TbDiemTotNghieps.Add(diem);
                            }

                        }
                        //Điểm môn tùy chọn
                        if (Request.Form["ddlMarkRecruitmentBasic"].Trim() != "")
                        {
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(Request.Form["ddlSubjectRecruitmentBasic"].Trim()), Diem = double.Parse(Request.Form["ddlMarkRecruitmentBasic"].Trim()) };
                            db.TbDiemTotNghieps.Add(diem);
                        }
                        //item.MaHeDaoTao = Int32.Parse(Request.Form["HDT"]);
                    }
                    else
                    {
                        // Điểm 3 môn Toán, Văn, Anh
                        string[] MangMaMon1 = Request.Form["SubjectRecruitment"].Split(',');
                        string[] MangDiemMon1 = Request.Form["MarkRecruitment"].Split(',');
                        string ten = "";
                        for (int i = 0; i < MangMaMon1.Length; i++)
                        {
                            if (MangDiemMon1[i].Trim() != "")
                            {
                                ten = MangMaMon1[i];
                                var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon, Diem = double.Parse(MangDiemMon1[i].Trim()) };
                                db.TbDiemTotNghieps.Add(diem);
                            }

                        }
                        //Điểm môn tùy chọn
                        if (Request.Form["ddlMarkRecruitment"].Trim() != "")
                        {
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(Request.Form["ddlSubjectRecruitment"].Trim()), Diem = double.Parse(Request.Form["ddlMarkRecruitment"].Trim()) };
                            db.TbDiemTotNghieps.Add(diem);
                        }
                        // Điểm môn thi thêm
                        string[] MangMaMon3 = Request.Form["IDInput"].Split(',');
                        string[] MangDiemMon3 = Request.Form["MarkSubject"].Split(',');
                        for (int i = 0; i < MangMaMon3.Length; i++)
                        {
                            if (MangDiemMon3[i].Trim() != "")
                            {
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(MangMaMon3[i]), Diem = double.Parse(MangDiemMon3[i]) };
                                db.TbDiemTotNghieps.Add(diem);
                            }

                        }

                    }
                    // Lưu hệ khác
                    if (HeCaoDang)
                    {
                        db.TbThiSinh_HeDaoTaos.Add(new TbThiSinh_HeDaoTao { MaHeDaoTao = 1, MaTS = item.MaTS });
                    }
                    if (HeTrungCap)
                    {
                        db.TbThiSinh_HeDaoTaos.Add(new TbThiSinh_HeDaoTao { MaHeDaoTao = 2, MaTS = item.MaTS });
                    }
                    item.MaHeDaoTao = Int32.Parse(Request.Form["HDT"]);
                    db.TbThiSinhs.Add(item);
                    nguoidung = new TbNguoiDung { TenDangNhap = item.MaTS, MaQuyen = 3, MatKhau = DuLieuChung.MaHoaMD5("123456"), RandomPass = "1234zxcv", KhoaTaiKhoan = 0 };
                    db.TbNguoiDungs.Add(nguoidung);
                    SaveChanges(db);
                    //}                    
                }
            }
            
            return RedirectToAction("CandidateList", "CandidateManagement");

        }
        public ActionResult Step2_Examination()
        {
            //TbThiSinh ThiSinh = new TbThiSinh();
            //if (ModelState.IsValid)
            //{
            //    if (Session["TenDangNhap"] != null)
            //        MaTS = MaTS ?? Session["TenDangNhap"].ToString();

            //    if (MaTS == null)
            //    {
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
            //ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
            //ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
            ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
            ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
            //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
            //ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
            //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
            //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
            //ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
            //ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");


            //if (Request.IsAjaxRequest() || MaTS != null)
            return PartialView();

            //return View(ThiSinh);
        }
        public ActionResult Step2_Recruiting()
        {
            //TbThiSinh ThiSinh = new TbThiSinh();
            //if (ModelState.IsValid)
            //{
            //    if (Session["TenDangNhap"] != null)
            //        MaTS = MaTS ?? Session["TenDangNhap"].ToString();

            //    if (MaTS == null)
            //    {
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
            //ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
            //ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
            ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
            ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
            //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
            ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
            //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
            //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
            //ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
            //ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");


            //if (Request.IsAjaxRequest() || MaTS != null)
            return PartialView();

            //return View(ThiSinh);
        }
        public ActionResult Step2_RecruitingBasic()
        {
            //TbThiSinh ThiSinh = new TbThiSinh();
            //if (ModelState.IsValid)
            //{
            //    if (Session["TenDangNhap"] != null)
            //        MaTS = MaTS ?? Session["TenDangNhap"].ToString();

            //    if (MaTS == null)
            //    {
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
            //ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
            //ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
            //ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
            ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
            ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
            //ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
            ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
            //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
            //ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
            //ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
            //ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
            ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");


            //if (Request.IsAjaxRequest() || MaTS != null)
            return PartialView();

            //return View(ThiSinh);
        }
        #endregion

        #region Registration Form Vocation
        public ActionResult RegistrationFormVocation(string TrainingSystem)
        {

            TbThiSinh ThiSinh = new TbThiSinh();
            ViewBag.HDT = TrainingSystem;
            if (ModelState.IsValid)
            {
                //if (Session["TenDangNhap"] != null)
                //    MaTS = MaTS ?? Session["TenDangNhap"].ToString();

                if (ThiSinh.MaTS == null)
                {
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                    ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                    ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.Where(m => m.TenMon.ToLower() != "Toán".ToLower() && m.TenMon.ToLower() != "Ngữ văn".ToLower() && m.TenMon.ToLower() != "Tiếng Anh".ToLower()).ToList(), "MaMon", "TenMon");
                    ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh");
                    ViewBag.Huyen = new SelectList(db.TbHuyens.ToList(), "MaHuyen", "TenHuyen");
                    ViewBag.Nganh = new SelectList(db.TbNganhs.ToList(), "IDNganh", "TenNganh");
                    ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.ToList(), "MaChuyenNganh", "TenChuyenNganh");
                    ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.ToList(), "IDTruong", "TenTruong");
                    //ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH");
                    //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc");
                    ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS");
                    ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc");
                    ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong");
                    ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi");
                    ViewBag.HeDaoTao = new SelectList(db.TbHeDaoTaos.ToList(), "MaHeDaoTao", "TenHeDaoTao");
                }
            }


            if (Request.IsAjaxRequest())
                return PartialView(ThiSinh);

            return View(ThiSinh);
        }
        [HttpPost]
        public ActionResult RegistrationFormVocation(TbThiSinh item, bool HeTrungCap = false, bool HeCaoDang = false)
        {
            if (item != null)
            {
                TbNguoiDung nguoidung;
                item.NgayDangKi = DateTime.Now;
                //item.NgaySinh = DateTime.Now;
                if (item.MaTS != null)
                {
                    db.Entry(item).State = EntityState.Modified;
                    db.SaveChanges();
                }
                else
                {
                    //if (ModelState.IsValid)
                    //{
                    item.MaTS = GetID();
                    item.NgayDongTien = DateTime.Now;
                    item.NgayHoanThanhDK = DateTime.Now;
                    var truongdh = db.TbTruongDHs.Where(m => m.TenTruongDH.ToLower() == "Trường ĐH Điện Lực".ToLower()).FirstOrDefault().MaTruongDH;
                    item.MaTruongDH = truongdh;
                    //var hedt = db.TbHeDaoTaos.Select(m => m.MaHeDaoTao);
                    if (HeCaoDang && HeTrungCap)
                    {
                        var hedt = db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.ToLower() == "Cao đẳng nghề".ToLower()).FirstOrDefault().MaHeDaoTao;
                        item.MaHeDaoTao = hedt;
                        db.TbThiSinh_HeDaoTaos.Add(new TbThiSinh_HeDaoTao { MaHeDaoTao = 2, MaTS = item.MaTS });
                    }
                    if (HeCaoDang)
                    {
                        var hedt = db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.ToLower() == "Cao đẳng nghề".ToLower()).FirstOrDefault().MaHeDaoTao;
                        item.MaHeDaoTao = hedt;
                    }
                    if (HeTrungCap)
                    {
                        var hedt = db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.ToLower() == "Trung cấp Chính quy".ToLower()).FirstOrDefault().MaHeDaoTao;
                        item.MaHeDaoTao = hedt;
                    }
                    item.MaHeDaoTao = int.Parse(Request.Form["RequestTS"]);

                    //item.MaHeDaoTao = HDT;
                    //item.MaHeDaoTao = LoadTrainingSystem;
                    db.TbThiSinhs.Add(item);
                    nguoidung = new TbNguoiDung { TenDangNhap = item.MaTS, MaQuyen = 3, MatKhau = DuLieuChung.MaHoaMD5("123456"), RandomPass = "1234zxcv", KhoaTaiKhoan = 0 };
                    db.TbNguoiDungs.Add(nguoidung);
                    SaveChanges(db);
                    //}                    
                }
            }
            return RedirectToAction("CandidateList", "CandidateManagement");

        }
        #endregion

        #region Edit Registration
        public ActionResult EditRegistration(string id)
        {
            ViewBag.HeTrungCap = false;
            ViewBag.HeCaoDang = false;
            TbThiSinh InfoCandidate = new TbThiSinh();
            InfoCandidate = db.TbThiSinhs.FirstOrDefault(m => m.MaTS == id);
            //item.NgaySinh = InfoCandidate.NgaySinh;
            ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc", InfoCandidate.MaDanToc);
            ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong", InfoCandidate.MaDoiTuong);
            var matinh = (from c in db.TbThiSinhs
                          join d in db.TbHuyens on c.MaHuyen equals d.MaHuyen
                          //join e in db.TbTinhs on d.MaTinh equals e.MaTinh
                          where c.MaTS == id
                          select d).FirstOrDefault();
            ViewBag.Tinh = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh", matinh.MaTinh);
            ViewBag.Huyen = new SelectList(db.TbHuyens.Where(m => m.MaTinh == matinh.MaTinh).ToList(), "MaHuyen", "TenHuyen", InfoCandidate.MaHuyen);
            var IDNganh = (from c in db.TbThiSinhs
                           join d in db.TbChuyenNganhs on c.MaChuyenNganh equals d.MaChuyenNganh
                           where c.MaTS == id
                           select d).FirstOrDefault().IDNganh;
            var makhoithi = db.TbChuyenNganhs.Include(m => m.TbNganh).Where(m => m.IDNganh == IDNganh).FirstOrDefault().TbNganh.MaKhoiThi;
            ViewBag.KhoiThi = new SelectList(db.TbKhoiThis.ToList(), "MaKhoiThi", "TenKhoiThi", makhoithi);
            ViewBag.HeDaoTao1 = new SelectList(db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.ToLower() == "đại học chính quy" || m.TenHeDaoTao.ToLower() == "cao đẳng chính quy").ToList(), "MaHeDaoTao", "TenHeDaoTao", InfoCandidate.MaHeDaoTao);
            ViewBag.HeDaoTao2 = new SelectList(db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.ToLower() == "cao đẳng nghề" || m.TenHeDaoTao.ToLower() == "trung cấp chính quy").ToList(), "MaHeDaoTao", "TenHeDaoTao", InfoCandidate.MaHeDaoTao);
            var manganh = (from m in db.TbChuyenNganhs where (m.MaChuyenNganh == InfoCandidate.MaChuyenNganh) select m).First().IDNganh;
            ViewBag.Nganh = new SelectList(db.TbNganhs.Where(m => m.MaKhoiThi == makhoithi).ToList(), "IDNganh", "TenNganh", manganh);
            ViewBag.ChuyenNganh = new SelectList(db.TbChuyenNganhs.Where(m => m.IDNganh == manganh).ToList(), "MaChuyenNganh", "TenChuyenNganh", InfoCandidate.MaChuyenNganh);
            var matinh2 = (from c in db.TbThiSinhs
                           join d in db.TbTruongTHPTs on c.IDTruong equals d.IDTruong
                           //join e in db.TbTinhs on d.MaTinh equals e.MaTinh
                           where c.MaTS == id
                           select d).FirstOrDefault().MaTinh;
            //var matinh2 = db.TbThiSinhs.Include(m => m.IDTruong).Where(m => m.MaTS == id).FirstOrDefault().TbHuyen.MaTinh;
            ViewBag.TruongTHPT = new SelectList(db.TbTruongTHPTs.Where(m => m.MaTinh == matinh2).ToList(), "IDTruong", "TenTruong", InfoCandidate.IDTruong);
            ViewBag.TruongDH = new SelectList(db.TbTruongDHs.ToList(), "MaTruongDH", "TenTruongDH", InfoCandidate.MaTruongDH);
            ViewBag.TinhTruong = new SelectList(db.TbTinhs.ToList(), "MaTinh", "TenTinh", matinh2);
            //ViewBag.KhuVuc = new SelectList(db.TbKhuVucs.ToList(), "MaKhuVuc", "TenKhuVuc", ThiSinh.MaKhuVuc);
            var mamon = (from c in db.TbThiSinhs
                         join d in db.TbDiemTotNghieps on c.MaTS equals d.MaTS
                         where c.MaTS == id
                         select d).FirstOrDefault();
            if (mamon != null)
            {
                ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.ToList(), "MaMon", "TenMon", mamon.MaMon);
            }
            else
            {
                ViewBag.MonTotNghiep = new SelectList(db.TbMonTotNghieps.ToList(), "MaMon", "TenMon");
            }
            ViewBag.XepLoaiHS = new SelectList(db.TbXepLoaiHS.ToList(), "MaXepLoaiHS", "TenXepLoaiHS", InfoCandidate.MaXepLoaiHS);
            ViewBag.DanToc = new SelectList(db.TbDanTocs.ToList(), "MaDanToc", "TenDanToc", InfoCandidate.MaDanToc);
            ViewBag.DoiTuongUuTien = new SelectList(db.TbDoiTuongUuTiens.ToList(), "MaDoiTuong", "TenDoiTuong", InfoCandidate.MaDoiTuong);


            // Load Toán, Anh, Văn
            TbDiemTotNghiep Mark = new TbDiemTotNghiep();
            var ListMark = db.TbDiemTotNghieps.Where(m => m.MaTS == id);
            //var ListMark2 = db.TbDiemTotNghieps.Join();
            if (ListMark.Count() != 0)
            {
                foreach (var a in ListMark)
                {
                    var Subject = db.TbMonTotNghieps.FirstOrDefault(m => m.MaMon == a.MaMon).TenMon;
                    if (Subject.ToLower() == "toán")
                    {
                        ViewBag.Toan = a.Diem.ToString();
                    }
                    if (Subject.ToLower() == "tiếng anh")
                    {
                        ViewBag.Anh = a.Diem.ToString();
                    }
                    if (Subject.ToLower() == "ngữ văn")
                    {
                        ViewBag.Van = a.Diem.ToString();
                    }
                }
            }
            var TS_HDT = db.TbThiSinh_HeDaoTaos.Where(m => m.MaTS == id).Select(m => m.MaHeDaoTao);
            foreach (var a in TS_HDT)
            {
                if (db.TbHeDaoTaos.First(m => m.MaHeDaoTao == a).TenHeDaoTao.ToLower() == "cao đẳng nghề")
                {
                    ViewBag.HeCaoDang = true;
                }
                if (db.TbHeDaoTaos.First(m => m.MaHeDaoTao == a).TenHeDaoTao.ToLower() == "cao đẳng nghề")
                {
                    ViewBag.HeTrungCap = true;
                }

            }
            ViewBag.NgayHoanThanhDK = InfoCandidate.NgayHoanThanhDK.ToString();
            ViewBag.NgayDangKi = InfoCandidate.NgayDangKi.ToString();
            ViewBag.NgayDongTien = InfoCandidate.NgayDongTien.ToString();
            ViewBag.LanSuaCuoi = InfoCandidate.LanSuaCuoi.ToString();
            return View(InfoCandidate);
        }

        [HttpPost]
        public ActionResult EditRegistration(TbThiSinh item, bool HeTrungCap = false, bool HeCaoDang = false)
        {
            if (item.MaTS != null)
            {
                var InfoCandidate = db.TbThiSinhs.AsNoTracking().First(n => n.MaTS == item.MaTS);
                string TSName = db.TbHeDaoTaos.AsNoTracking().First(m => m.MaHeDaoTao == InfoCandidate.MaHeDaoTao).TenHeDaoTao.ToLower();
                if (TSName == "đại học chính quy" || TSName == "cao đẳng chính quy")
                {
                    // Điểm tốt nghiệp
                    TbDiemTotNghiep diem;
                    //toán văn anh
                    string[] MangMaMon = Request.Form["Subject"].Split(',');
                    string[] MangDiemMon = Request.Form["Mark"].Split(',');
                    string ten = "";
                    var listmark = db.TbDiemTotNghieps.Where(m => m.MaTS == item.MaTS);
                    if (listmark != null)
                    {
                        foreach (var a in listmark)
                        {

                            db.TbDiemTotNghieps.Remove(a);
                        }
                        db.SaveChanges();
                    }
                    for (int i = 0; i < MangMaMon.Length; i++)
                    {
                        if (MangDiemMon[i].Trim() != "")
                        {
                            ten = MangMaMon[i];
                            var mamon = db.TbMonTotNghieps.Where(m => m.TenMon == ten).FirstOrDefault().MaMon;
                            diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = mamon, Diem = double.Parse(MangDiemMon[i].Trim()) };
                            db.TbDiemTotNghieps.Add(diem);
                        }
                    }

                    //môn còn lại
                    if (Request.Form["Subject1"] != null && Request.Form["Mark1"] != null)
                    {
                        string[] MangMaMon2 = Request.Form["Subject1"].Split(',');
                        string[] MangDiemMon2 = Request.Form["Mark1"].Split(',');
                        for (int i = 0; i < MangMaMon2.Length; i++)
                        {
                            if (MangDiemMon2[i].Trim() != "")
                            {
                                diem = new TbDiemTotNghiep { MaTS = item.MaTS, MaMon = Int32.Parse(MangMaMon2[i]), Diem = double.Parse(MangDiemMon2[i]) };
                                db.TbDiemTotNghieps.Add(diem);
                            }
                        }
                    }

                    // Thí sinh hệ đào tạo

                    var listTS = db.TbThiSinh_HeDaoTaos.Where(m => m.MaTS == item.MaTS);
                    if (listTS != null)
                    {
                        foreach (var a in listTS)
                        {

                            db.TbThiSinh_HeDaoTaos.Remove(a);
                        }
                        db.SaveChanges();
                    }
                    if (HeCaoDang)
                    {
                        var Ma1 = db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.ToLower() == "Cao đẳng nghề".ToLower()).FirstOrDefault().MaHeDaoTao;
                        db.TbThiSinh_HeDaoTaos.Add(new TbThiSinh_HeDaoTao { MaHeDaoTao = Ma1, MaTS = item.MaTS });
                        db.SaveChanges();
                    }
                    if (HeTrungCap)
                    {
                        var Ma2 = db.TbHeDaoTaos.Where(m => m.TenHeDaoTao.ToLower() == "Trung cấp chính quy".ToLower()).FirstOrDefault().MaHeDaoTao;
                        db.TbThiSinh_HeDaoTaos.Add(new TbThiSinh_HeDaoTao { MaHeDaoTao = Ma2, MaTS = item.MaTS });
                        db.SaveChanges();
                    }
                }
                if (item.NgayDongTien != null)
                {
                    item.NgayDongTien = item.NgayDongTien;
                }
                if (item.NgayHoanThanhDK != null)
                {
                    item.NgayHoanThanhDK = item.NgayHoanThanhDK;
                }
                item.MaHeDaoTao = InfoCandidate.MaHeDaoTao;
                item.MaChuyenNganh = InfoCandidate.MaChuyenNganh;
                item.NgayDangKi = db.TbThiSinhs.AsNoTracking().First(m => m.MaTS == item.MaTS).NgayDangKi;
                //item.NgayHoanThanhDK = DateTime.Now;
                item.LanSuaCuoi = DateTime.Now;
                db.TbThiSinhs.AsNoTracking();

                db.Entry(item).State = EntityState.Modified;
                db.SaveChanges();
            }

            return RedirectToAction("CandidateList", "CandidateManagement");
        }
        #endregion
        #endregion
    }
}